<?php
namespace App\Controllers;
class Hockey extends BaseController
{
    public function index()
    {
        
        $places = new \App\Models\Players();
        $records = $places->findAll();

        
        $data['title'] = 'Travel Destinations';
        $data['heading'] = 'A List of Travel Destinations';
        $data['footer'] = 'Copyright zhengjingjun';
        $data['records'] = $records;

        return view('hockey/index', $data);
    }
    public function update($id)
    {   $places = new \App\Models\Players();
        // Validate form input
        $rules = [
            'name' => 'required|min_length[3]',
            'city' => 'required',
            'powers' => 'required',
            'weapon' => 'required'
        ];
    
        if ($this->validate($rules)) {
           
            $data = [
                'name' => $this->request->getPost('name'),
                'city' => $this->request->getPost('city'),
                'powers' => $this->request->getPost('powers'),
                'weapon' => $this->request->getPost('weapon')
            ];
    
          
            $playersModel = new \App\Models\Players();
            if ($playersModel->update($id, $data)) {
                return redirect()->to(base_url('hockey/showme/' . $id))->with('success', 'Hero updated successfully.');
            } else {
                throw new \CodeIgniter\Exceptions\PageNotFoundException("Failed to update hero with id: $id");
            }
        } else {
            $record = $places->find($id);
            $fields = [
                'title' => $record['name'],
                'heading' => $record['name'],
                'footer' => 'Copyright xieyuhang',
                'record' => $record,
                'errors' => $this->validator->getErrors(),
                'editMode' => true
            ];
    
            $parser = \Config\Services::parser();
            return $parser->setData($fields)
                ->render('templates/top') .
                view('hockey/editpage', $fields) .
                $parser->setData($fields)
                    ->render('templates/bottom');
        }
    }

    public function create()
    {
        helper('form'); 

        $data = [
            'title' => 'Create New Hero',
            'heading' => 'Create New Hero',
            'footer' => 'Copyright zhengjingjun',
            'editMode' => false
        ];

        return  view('hockey/create', $data);
    }
    public function edit($id)
    {
        $places = new \App\Models\Players();
        $record = $places->find($id);
    
        if (!$record) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException("No hero found with id: $id");
        }
    
        // Prepare data for view
        $fields = [
            'title' => $record['name'],
            'heading' => $record['name'],
            'footer' => 'Copyright xieyuhang',
            'record' => $record,
            'editMode' => true
        ];
    
     
        $parser = \Config\Services::parser();
    
        return $parser->setData($fields)
            ->render('templates/top') .
            view('hockey/editplayer', $fields) .
            $parser->setData($fields)
                ->render('templates/bottom');
    }
    public function showme($id)
    {
        $places = new \App\Models\Players();
        $record = $places->find($id);
    
        if (!$record) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException("No travel destination found with id: $id");
        }
    
        $table = new \CodeIgniter\View\Table();
    
        $table->setHeading('Field', 'Value');
    
        $table->addRow('Id', $record['id']);
        $table->addRow('Name', $record['name']);
        $table->addRow('City', $record['city']);
        $table->addRow('powers', $record['powers']);
        $table->addRow('weapon', $record['weapon']);
        $table->addRow('Image', '<img src="/image/' . $record['image'] . '" >');
    
        
        $template = [
            'table_open' => '<table cellpadding="5px">',
            'cell_start' => '<td style="border: 1px solid #dddddd;">',
            'row_alt_start' => '<tr style="background-color:#dddddd">',
        ];
        $table->setTemplate($template);
    
      
        $fields = [
            'title' => $record['name'],
            'heading' => $record['name'],
            'footer' => 'Copyright zhengjingjun',
            'editLink' => base_url('hockey/edit/' . $id),
            'deleteLink' => base_url('hockey/delete/' . $id), // 添加删除链接
        ];
    
       
        $parser = \Config\Services::parser();
        return $parser->setData($fields)
            ->render('templates/top') .
            $table->generate() .
            "<p><a href='" . esc($fields['editLink']) . "'>Edit</a> | 
             <a href='" . esc($fields['deleteLink']) . "' onclick=\"return confirm('Are you sure you want to delete this hero?');\">Delete</a></p>" .
            $parser->setData($fields)
                ->render('templates/bottom');
    }
    public function store()
    {
        helper('form'); 

       
        if (!$this->validate([
            'name' => 'required|min_length[3]|max_length[255]',
            'description' => 'max_length[65535]',
            'link' => 'max_length[255]',
            'image' => 'max_length[255]',
            'city' => 'max_length[255]',
            'powers' => 'max_length[65535]',
            'weapon' => 'max_length[255]',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        // 获取表单数据
        $data = [
            'name' => $this->request->getPost('name'),
            'description' => $this->request->getPost('description'),
            'link' => $this->request->getPost('link'),
            'image' => $this->request->getPost('image'),
            'city' => $this->request->getPost('city'),
            'powers' => $this->request->getPost('powers'),
            'weapon' => $this->request->getPost('weapon'),
        ];

        
        $playersModel = new \App\Models\Players();
        $insertID = $playersModel->insert($data);

        if ($insertID !== false) {
           
            return redirect()->to('/hockey')->with('success', 'Hero created successfully.');
        } else {
          
            return redirect()->back()->withInput()->with('error', 'Failed to create hero.');
        }
    }
    public function delete($id)
    {
        try {
            $playersModel = new \App\Models\Players();
    
            // Attempt to delete the record with a specific condition (where id = $id)
            if ($playersModel->builder->where('id', $id)->delete()) {
                return redirect()->to(base_url('hockey'))->with('success', 'Hero deleted successfully.');
            } else {
                return redirect()->back()->with('error', 'Failed to delete hero.');
            }
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Error deleting hero: ' . $e->getMessage());
        }
    }
    public function info()
    {
        $data['title'] = 'About Me';
        return view('hockey/info', $data);
    }
}

